package com.link.base.tencent.corpwx.externalcontact.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.agent.service.AgentService;
import com.link.base.tencent.corpwx.agent.util.AgentIdUtil;
import com.link.base.tencent.corpwx.externalcontact.dao.mybatis.mapper.ExternalContactMapper;
import com.link.base.tencent.corpwx.externalcontact.model.ExternalContact;
import com.link.base.tencent.corpwx.externalcontact.model.ExternalFollowTag;
import com.link.base.tencent.corpwx.externalcontact.model.ExternalFollowUser;
import com.link.base.tencent.corpwx.externalcontact.util.ExternalContactUtil;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.cllog.LCLogger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 外部联系人服务，该服务所涉及的应用为外部联系人应用，对应企业微信应用管理上的【客户联系】
 *
 * @author 欧阳振强
 * @date 2020-01-02 15:22:51.0
 */
@Service
public class ExternalContactServiceImpl extends BasicServiceImpl<ExternalContact> implements ExternalContactService {
    private static final String OP_ADD = "add";
    private static final String OP_UPDATE = "update";
    private static final String OP_DEL = "del";
    private static final String STR_1 = "1";
    private static final String STR_2 = "2";
    @Resource
    private ExternalContactMapper externalContactMapper;
    @Resource
    private AgentService agentService;
    @Resource
    private KeyGenerateService keyGenerateService;
    @Resource
    private ExternalFollowUserService externalFollowUserService;
    @Resource
    private ExternalFollowTagService externalFollowTagService;
    
    @Override
    public BasicMapper<ExternalContact> getBasicMapper() {
        return externalContactMapper;
    }

    @Override
    public List<String> getAccountListByApi() throws Exception {
        List<String> userIdList = new ArrayList<>();
        String accessToken = agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID);
        // 获取配置了客户联系功能的成员列表
        JSONObject followUser = ExternalContactUtil.getFollowUserList(accessToken);
        JSONArray followUserList = followUser.getJSONArray("follow_user");
        if (followUserList != null) {
            for (int i = 0; i < followUserList.size(); i++) {
                accessToken = agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID);
                // 通过成员Id获取成员下的客户列表
                JSONObject externalContact = ExternalContactUtil.getExternalContactList(accessToken, followUserList.getString(i));
                JSONArray externalContactList = externalContact.getJSONArray("external_userid");
                if (externalContactList != null) {
                    for (int j = 0; j < externalContactList.size(); j++) {
                        userIdList.add(externalContactList.getString(j));
                    }
                }
            }
        }
        // 多人可能同时跟进同一个客户，因此需要去重
        List<String> finalUserIdList = new ArrayList<>();
        Map<String, String> map = new HashMap<>(128);
        for (String item: userIdList) {
            if (map.get(item) == null) {
                map.put(item, item);
                finalUserIdList.add(item);
            }
        }
        LCLogger.info().withMessageKey("ExternalContactService").withMessage("客户总数 -> " + finalUserIdList.size()).flush();
        return finalUserIdList;
    }

    @Override
    public ExternalContact getAccountItemByApi(String externalContactId) throws Exception {
        String accessToken = agentService.getExistAccessToken(AgentIdUtil.CORPWX_ACCOUNT_AGENTID);
        ExternalContact account = new ExternalContact();
        JSONObject externalContact = ExternalContactUtil.getExternalContact(accessToken, externalContactId);
        // 基础信息
        JSONObject baseInfo = externalContact.getJSONObject("external_contact");
        if (baseInfo == null) {
            throw new BasicServiceException("未获取到企业微信客户信息，请检查是否添加了该客户或添加后已经删除了好友关系！");
        }
        account.setExternalUserId(baseInfo.getString("external_userid"));
        account.setName(baseInfo.getString("name"));
        account.setPosition(baseInfo.getString("position"));
        account.setAvatar(baseInfo.getString("avatar"));
        account.setCorpName(baseInfo.getString("corp_name"));
        account.setCorpFullName(baseInfo.getString("corp_full_name"));
        account.setType(baseInfo.getString("type"));
        String gender = baseInfo.getString("gender");
        if (STR_1.equals(gender)) {
            account.setGender("MALE");
        } else if (STR_2.equals(gender)) {
            account.setGender("FEMALE");
        }
        account.setUnionId(baseInfo.getString("unionid"));
        List<ExternalFollowUser> externalFollowUserList = new ArrayList<>();
        // 跟进人信息
        JSONArray followUserList = externalContact.getJSONArray("follow_user");
        if (followUserList != null) {
            for (int i = 0; i < followUserList.size(); i++) {
                JSONObject followUser = followUserList.getJSONObject(i);
                ExternalFollowUser externalFollowUser = new ExternalFollowUser();
                externalFollowUser.setUserId(followUser.getString("userid"));
                externalFollowUser.setRemark(followUser.getString("remark"));
                externalFollowUser.setDescription(followUser.getString("description"));
                externalFollowUser.setCreateTime(followUser.getString("createtime"));
                externalFollowUser.setRemarkCorpName(followUser.getString("remark_corp_name"));
                externalFollowUser.setState(followUser.getString("state"));
                // 备注电话号码
                JSONArray remarkMobiles = followUser.getJSONArray("remark_mobiles");
                StringBuffer remarkMobile = new StringBuffer();
                for (int j = 0; j < remarkMobiles.size(); j++) {
                    remarkMobile.append(remarkMobiles.getString(j) + ";");
                }
                externalFollowUser.setRemarkMobiles(remarkMobile.toString());
                // 标签
                List<ExternalFollowTag> externalFollowTagList = new ArrayList<>();
                JSONArray tags = followUser.getJSONArray("tags");
                if (tags != null) {
                    for (int k = 0; k < tags.size(); k++) {
                        JSONObject tag = tags.getJSONObject(k);
                        ExternalFollowTag externalFollowTag = new ExternalFollowTag();
                        externalFollowTag.setGroupName(tag.getString("group_name"));
                        externalFollowTag.setTagName(tag.getString("tag_name"));
                        externalFollowTag.setType(tag.getString("type"));
                        externalFollowTagList.add(externalFollowTag);
                    }
                }
                externalFollowUser.setTagList(externalFollowTagList);
                externalFollowUserList.add(externalFollowUser);
            }
        }
        account.setFollowUserList(externalFollowUserList);
        return account;
    }

    @Override
    public ExternalContact getAccountItemByLink(String externalContactId) throws Exception {
        ExternalContact externalContact = new ExternalContact();
        externalContact.setExternalUserId(externalContactId);
        ExternalContact existAccount = externalContactMapper.getExternalContactById(externalContact);
        if (existAccount == null) {
            // 不存在直接返回null
            return null;
        } else {
            // 存在则需要查询外部联系人下的跟进人和跟进人标签
            List<ExternalFollowUser> externalFollowUserList = externalFollowUserService.listExternalFollowUserByHeadId(existAccount.getId());
            for (ExternalFollowUser item: externalFollowUserList) {
                List<ExternalFollowTag> externalFollowTagList = externalFollowTagService.listExternalFollowTagByHeadId(item.getId());
                item.setTagList(externalFollowTagList);
            }
            existAccount.setFollowUserList(externalFollowUserList);
        }
        return existAccount;
    }

    @Override
    public void syncSingleAccountInfoFromWx(String externalContactId) throws Exception {
        // 从接口获取外部联系人详情
        ExternalContact account = this.getAccountItemByApi(externalContactId);
        // 从Link获取外部联系人详情
        ExternalContact existAccount = this.getAccountItemByLink(externalContactId);
        if (existAccount == null) {
            // 新建外部联系人
            Long accountId = keyGenerateService.keyGenerate();
            account.setId(accountId);
            externalContactMapper.insert(account);
            List<ExternalFollowUser> externalFollowUserList = account.getFollowUserList();
            for (ExternalFollowUser item: externalFollowUserList) {
                // 新建跟进人
                item.setHeadId(accountId);
                Long followUserId = keyGenerateService.keyGenerate();
                item.setId(followUserId);
                externalFollowUserService.insert(item);
                // 新建跟进人-标签
                externalFollowTagService.insertByList(item.getTagList(), followUserId);
            }
        } else {
            // 更新外部联系人基础信息
            account.setId(existAccount.getId());
            externalContactMapper.update(account);
            // 获取需要处理的跟进人，包括新建、更新、删除
            List<ExternalFollowUser> opExternalFollowUserList =
                externalFollowUserService.opExternalFollowUserList(account.getFollowUserList(), existAccount.getFollowUserList());
            for (ExternalFollowUser externalFollowUserItem: opExternalFollowUserList) {
                String externalFollowUserOp = externalFollowUserItem.getOp();
                if (OP_ADD.equals(externalFollowUserOp)) {
                    // 新建跟进人
                    externalFollowUserItem.setHeadId(existAccount.getId());
                    Long followUserId = keyGenerateService.keyGenerate();
                    externalFollowUserItem.setId(followUserId);
                    externalFollowUserService.insert(externalFollowUserItem);
                    // 新建跟进人-标签
                    externalFollowTagService.insertByList(externalFollowUserItem.getTagList(), followUserId);
                } else if (OP_UPDATE.equals(externalFollowUserOp)) {
                    // 更新跟进人
                    externalFollowUserService.update(externalFollowUserItem);
                    // 更新跟进人-标签
                    List<ExternalFollowTag> externalFollowTagList = externalFollowUserItem.getTagList();
                    for (ExternalFollowTag externalFollowTagItem: externalFollowTagList) {
                        String externalFollowTagOp = externalFollowTagItem.getOp();
                        if (OP_ADD.equals(externalFollowTagOp)) {
                            externalFollowTagItem.setFollowUserId(externalFollowUserItem.getId());
                            externalFollowTagItem.setId(keyGenerateService.keyGenerate());
                            externalFollowTagService.insert(externalFollowTagItem);
                        } else if (OP_DEL.equals(externalFollowTagOp)) {
                            externalFollowTagService.deleteById(externalFollowTagItem);
                        }
                    }
                } else if (OP_DEL.equals(externalFollowUserOp)) {
                    // 删除跟进人
                    externalFollowUserService.deleteById(externalFollowUserItem);
                    // 删除跟进人-标签
                    externalFollowTagService.delByList(externalFollowUserItem.getTagList());
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncAllAccountInfoFromWx() throws Exception {
        List<String> externalContactIdList = getAccountListByApi();
        for (String item: externalContactIdList) {
            this.syncSingleAccountInfoFromWx(item);
        }
    }
}